<template>
  <div class="instance-management-container">
    <!-- 基础配置区域 -->
    <el-card class="status-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>基础配置</span>
          <el-button type="primary" @click="handleConfigAction">
            {{ isEditing ? "保存配置" : "修改配置" }}
          </el-button>
        </div>
      </template>
      <div class="config-form">
        <el-form :model="config" label-width="120px" :disabled="!isEditing">
          <div class="form-columns">
            <!-- 第一列：HTTPS配置 -->
            <div class="form-column">
              <el-form-item label="开启HTTPS">
                <el-switch v-model="config.UseHTTPS" />
              </el-form-item>
              <template v-if="config.UseHTTPS">
                <el-form-item label="HTTPSCertFile">
                  <el-input
                    v-model="config.HTTPSCertFile"
                    placeholder="请输入证书文件路径"
                  />
                </el-form-item>
                <el-form-item label="HTTPSKeyFile">
                  <el-input
                    v-model="config.HTTPSKeyFile"
                    placeholder="请输入密钥文件路径"
                  />
                </el-form-item>
                <el-form-item label="HttpsPort">
                  <el-input
                    v-model="config.HttpsPort"
                    placeholder="请输入HTTPS端口"
                  />
                </el-form-item>
              </template>
            </div>
            <!-- 第二列：中继服务器配置 -->
            <div class="form-column">
              <el-form-item label="中继服务">
                <el-switch v-model="config.UseRelay" />
              </el-form-item>
              <template v-if="config.UseRelay">
                <el-form-item label="Turn">
                  <el-input
                    v-model="config.turn"
                    placeholder="请输入Turn服务器地址"
                  />
                </el-form-item>
                <el-form-item label="Stun">
                  <el-input
                    v-model="config.stun"
                    placeholder="请输入Stun服务器地址"
                  />
                </el-form-item>
                <el-form-item label="Username">
                  <el-input
                    v-model="config.username"
                    placeholder="请输入用户名"
                  />
                </el-form-item>
                <el-form-item label="Credential">
                  <el-input
                    v-model="config.credential"
                    placeholder="请输入凭证"
                  />
                </el-form-item>
              </template>
            </div>
          </div>
          <!-- 开放端口配置 -->
          <div class="form-full-width">
            <el-form-item label="开放端口">
              <el-input
                v-model="config.PortLimit"
                placeholder="请输入开放端口，多个端口用逗号分隔"
              />
            </el-form-item>
          </div>
          <div class="form-full-width">
            <el-form-item label="定期重启">
              <el-switch v-model="config.isRestart" />
              <el-time-picker
                v-if="config.isRestart"
                v-model="config.restartTime"
                placeholder="选择重启时间"
                format="HH:mm"
                value-format="HH:mm"
                style="margin-left: 20px"
                @change="handleRestartTimeChange"
              />
              <el-button
                style="margin-left: 15px"
                type="primary"
                @click="handleRestartInstanceAll"
                >立即重启</el-button
              >
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 实例列表区域 -->
    <el-card class="status-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>实例列表</span>
          <el-button type="primary" @click="createNewInstance"
            >创建新实例</el-button
          >
        </div>
      </template>
      <div class="instance-grid">
        <el-empty
          v-if="!instances || instances.length === 0"
          description="暂无实例"
        />
        <el-card
          v-else
          v-for="instance in instances"
          :key="instance.id"
          class="instance-card"
          shadow="hover"
        >
          <div class="instance-status">
            <div
              class="status-indicator"
              :class="getStatusClass(instance.status)"
            >
              <div class="status-pulse"></div>
            </div>
            <span class="status-text">{{
              getStatusText(instance.status)
            }}</span>
          </div>
          <div class="instance-content">
            <h3 class="instance-name">{{ instance.name }}</h3>
            <p class="instance-connection">
              <el-tag
                :type="instance.isConnected ? 'success' : 'info'"
                size="small"
              >
                {{ instance.isConnected ? "已连接" : "未连接" }}
              </el-tag>
            </p>
          </div>
          <div class="instance-actions">
            <el-button
              :type="instance.status === 'running' ? 'warning' : 'primary'"
              @click="handleInstanceAction(instance)"
            >
              {{ instance.status === "running" ? "停止" : "启动" }}
            </el-button>
            <el-button type="info" @click="viewInstanceDetails(instance)"
              >详情</el-button
            >
          </div>
        </el-card>
      </div>
    </el-card>
    <!-- 实例详情弹窗 -->
    <InstanceDetail
      v-model:visible="detailVisible"
      :instance="currentInstance"
      @refresh="handleRefresh"
    />
    <!-- 新增实例弹窗 -->
    <InstanceAdd v-model:visible="addVisible" @refresh="handleRefresh" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import InstanceDetail from "./detail/index.vue";
import InstanceAdd from "./add/index.vue";
import { ElMessage, ElNotification } from "element-plus";
import {
  getInstanceConfig,
  setInstanceConfig,
  getInstanceList,
  startInstance,
  stopInstance,
  restartInstance,
} from "@/api/modules/ueInstance";
import { useWebSocket } from "@/hooks/socketClient";
const { connected, onMessage, disconnect } = useWebSocket(
  "ueInstance",
  import.meta.env.VITE_API_BASE_WS_URL
);
onMessage("signal_copy_completed", (data) => {
  ElNotification.success({
    title: "实例通知:",
    message: `${data.name} 已成功创建`,
  });
  // fetchProjects();
});

onMessage("instance_deleted", (data) => {
  ElNotification.success({
    title: "实例通知:",
    message: `${data.name} 已成功删除`,
  });
  fetchInstances();
});
onMessage("instance_started", (data) => {
  ElNotification.success({
    title: "实例通知:",
    message: `${data.name} 已成功启动`,
  });
  isStartting.value = false;
  fetchInstances();
});
onMessage("instance_restarted", (data) => {
  ElNotification.success({
    title: "实例通知:",
    message: `${data.name} 已成功重启`,
  });
  // 从队列中移除已重启的实例
  const index = restartQueue.value.findIndex(
    (instance) => instance._id === data.instanceId
  );
  if (index !== -1) {
    restartQueue.value.splice(index, 1);
    processRestartQueue();
  }
  fetchInstances();
});

onMessage("instance_stopped", (data) => {
  ElNotification.success({
    title: "实例通知:",
    message: `${data.name} 已成功停止`,
  });
  isStopping.value = false;
  fetchInstances();
});
onMessage("instance_delete_failed", (data) => {
  ElNotification.error({
    title: "实例通知:",
    message: `${data.name} 删除失败`,
  });
  fetchInstances();
});
onMessage("instance_start_failed", (data) => {
  ElNotification.error({
    title: "实例通知:",
    message: `${data.name} 启动失败`,
  });
  isStartting.value = false;
  fetchInstances();
});
onMessage("instance_restart_failed", (data) => {
  ElNotification.error({
    title: "实例通知:",
    message: `${data.name} 重启失败`,
  });
  // 从队列中移除已重启的实例
  const index = restartQueue.value.findIndex(
    (instance) => instance._id === data.instanceId
  );
  if (index !== -1) {
    restartQueue.value.splice(index, 1);
    processRestartQueue();
  }
  fetchInstances();
});
onMessage("instance_stop_failed", (data) => {
  ElNotification.error({
    title: "实例通知:",
    message: `${data.name} 停止失败`,
  });
  isStopping.value = false;
  fetchInstances();
});

onMessage("instance_connection_message", (data) => {
  if (data.status) {
    ElNotification.success({
      title: "连接通知:",
      message: `${data.name} :${data.message} `,
    });
  } else {
    ElNotification.error({
      title: "连接通知:",
      message: `${data.name} :${data.message} `,
    });
  }

  fetchInstances();
});
// 控制详情弹窗显示
const detailVisible = ref(false);
const currentInstance = ref(null);

// 控制新增弹窗显示
const addVisible = ref(false);

// 编辑状态控制
const isEditing = ref(false);

// 基础配置数据
const config = ref({});

const getConfig = () => {
  getInstanceConfig().then((res) => {
    console.log(res);
    // 合并服务器返回的数据与默认值
    config.value = { ...config.value, ...res.data };
    // config.value.PortLimit = config.value.PortLimit.join(",");
  });
};
const handleRestartTimeChange = (value) => {
  console.log("Selected restart time:", value);
};
onMounted(() => {
  getConfig();
  fetchInstances();
});
const instances = ref([]);
const fetchInstances = () => {
  getInstanceList().then((res) => {
    console.log(res);
    instances.value = res.data;
    if (detailVisible.value) {
      currentInstance.value = instances.value.find(
        (instance) => instance._id === currentInstance.value._id
      );
    }
  });
};
// 处理配置操作
const handleConfigAction = () => {
  if (isEditing.value) {
    // 处理端口为数组
    // if (typeof config.value.PortLimit !== "string") {
    //   config.value.PortLimit = config.value.PortLimit.split(",");
    // }

    setInstanceConfig(config.value).then((res) => {
      console.log(res);
      if (res.status === "success") {
        ElMessage.success("配置更新成功");
      } else {
        ElMessage.error("配置更新失败");
      }
    });
    // 保存成功后切换回非编辑状态
    isEditing.value = false;
  } else {
    // 进入编辑状态
    isEditing.value = true;
  }
};

// 获取状态对应的类名
const getStatusClass = (status) => {
  const statusMap = {
    stopped: "status-gray",
    running: "status-green",
    error: "status-red",
    starting: "status-blue",
    stopping: "status-orange",
    deleting: "status-orange",
    restarting: "status-blue",
  };
  return statusMap[status] || "status-gray";
};

// 获取状态文本
const getStatusText = (status) => {
  const statusTextMap = {
    stopped: "未启动",
    stopping: "停止中",
    running: "运行中",
    error: "故障",
    starting: "启动中",
    deleting: "删除中",
    restarting: "重启中",
  };
  return statusTextMap[status] || "未知状态";
};

// 处理实例操作
const isStartting = ref(false);
const isStopping = ref(false);
const handleInstanceAction = (instance) => {
  if (isStartting.value || isStopping.value) {
    ElMessage.warning("请先等待上一个指令完成后，再进行操作");
    return
  }
  if (instance.status === "running") {
    stopInstance({ instanceId: instance._id }).then((res) => {
      isStopping.value = true;
      console.log(res);
      fetchInstances();
    });
  } else if (instance.status === "stopped") {
    startInstance({ instanceId: instance._id }).then((res) => {
      isStartting.value = true;
      console.log(res);
      fetchInstances();
    });
  }
};

// 查看实例详情
const viewInstanceDetails = (instance) => {
  currentInstance.value = instance;
  detailVisible.value = true;
};

// 创建新实例
const createNewInstance = () => {
  addVisible.value = true;
};
const handleRefresh = () => {
  fetchInstances();
};
// 添加重启队列的响应式引用
const restartQueue = ref([]);
const isRestarting = ref(false);

// 处理重启队列
const processRestartQueue = () => {
  if (restartQueue.value.length === 0) {
    isRestarting.value = false;
    ElMessage.success("所有实例重启完成");
    return;
  }

  if (!isRestarting.value) return;

  const instance = restartQueue.value[0];
  restartInstance({ instanceId: instance._id }).then(() => {
    console.log(`开始重启实例: ${instance.name}`);
    fetchInstances();
  });
};
const handleRestartInstanceAll = () => {
  // 获取所有运行中的实例
  const runningInstances = instances.value.filter(
    (instance) => instance.status === "running"
  );

  if (runningInstances.length === 0) {
    ElMessage.warning("没有正在运行的实例需要重启");
    return;
  }

  // 初始化重启队列
  restartQueue.value = [...runningInstances];
  isRestarting.value = true;

  // 开始处理队列
  processRestartQueue();
};
</script>

<style scoped>
.instance-management-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.status-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.config-form {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 0;
}

.form-columns {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32px;
}

.form-column {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.form-full-width {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.instance-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.instance-grid :deep(.el-empty) {
  grid-column: 1 / -1;
  margin: 40px 0;
}

.instance-card {
  position: relative;
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.instance-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.instance-status {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.status-indicator {
  position: relative;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-pulse {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.8;
  }
  70% {
    transform: translate(-50%, -50%) scale(2);
    opacity: 0;
  }
  100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0;
  }
}

.status-gray {
  background: linear-gradient(145deg, #8a8a8a, #909399);
  box-shadow: 0 0 10px rgba(144, 147, 153, 0.5);
}

.status-gray .status-pulse {
  background-color: #909399;
}

.status-green {
  background: linear-gradient(145deg, #5ab534, #67c23a);
  box-shadow: 0 0 10px rgba(103, 194, 58, 0.5);
}

.status-green .status-pulse {
  background-color: #67c23a;
}

.status-red {
  background: linear-gradient(145deg, #f35555, #f56c6c);
  box-shadow: 0 0 10px rgba(245, 108, 108, 0.5);
}

.status-red .status-pulse {
  background-color: #f56c6c;
}

.status-blue {
  background: linear-gradient(145deg, #3a8ee6, #409eff);
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.status-blue .status-pulse {
  background-color: #409eff;
}
.status-orange {
  background: linear-gradient(145deg, #e6a23c, #f5a623);
  box-shadow: 0 0 10px rgba(245, 166, 35, 0.5);
}

.status-orange .status-pulse {
  background-color: #f5a623;
}
.status-text {
  font-size: 14px;
  color: #606266;
}

.instance-content {
  margin-bottom: 16px;
}

.instance-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
}

.instance-connection {
  margin: 8px 0 0 0;
  font-size: 14px;
}

.instance-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .instance-grid {
    grid-template-columns: 1fr;
  }

  .instance-management-container {
    padding: 16px;
  }

  .config-form {
    padding: 10px;
  }

  .form-columns {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .form-column {
    padding: 12px;
  }
}
</style>
